<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-row type="flex" justify="end">
          <el-button type="primary" style="height: 40px" @click="addPermBtn(1, '0')">添加权限</el-button>
        </el-row>

        <el-table border :data="permissionList" row-key="id">
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="code" label="标识" />
          <el-table-column prop="description" label="描述" />
          <el-table-column label="操作">
            <template v-slot="scope">
              <el-button type="text" @click="addPermBtn(2, scope.row.id)">添加</el-button>
              <el-button type="text" @click="editPermBtn(scope.row.id)">编辑</el-button>
              <el-button type="text" @click="delPermBtn(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 放置一个弹层 用来编辑新增节点 -->
        <el-dialog
          :title="isEdit ? '编辑权限点' : '新增权限点'"
          :visible="showDialog"
          @close="btnCancel"
        >
          <!-- 表单 -->
          <el-form ref="perForm" :model="formData" :rules="rules" label-width="120px">
            <el-form-item label="权限名称" prop="name">
              <el-input v-model="formData.name" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限标识" prop="code">
              <el-input v-model="formData.code" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限描述">
              <el-input v-model="formData.description" style="width:90%" />
            </el-form-item>
            <el-form-item label="开启">
              <el-switch
                v-model="formData.enVisible"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-form>
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button size="small" type="primary" @click="onSubmit">确定</el-button>
              <el-button size="small" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-dialog>

      </el-card>
    </div>
  </div>
</template>

<script>
import { getPermissionList, addPermission, updatePermission, getPermissionDetail, delPermission } from '@/api/permission'
// 转化树形结构
import { transListToTree } from '@/utils'
export default {
  name: 'Permission',
  data() {
    // 同级不同名
    const validName = (rule, value, callback) => {
      let existNameList = this.originList.filter(item => item.pid === this.formData.pid)
      if (this.isEdit) {
        existNameList = this.originList.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id)
      }
      existNameList.map(item => item.name.trim()).includes(value) ? callback(new Error(`权限名称 ${value} 重复`)) : callback()
    }
    // 所有标示不同
    const validCode = (rule, value, callback) => {
      let existCodeList = this.originList
      if (this.isEdit) {
        existCodeList = this.originList.filter(item => item.id !== this.formData.id)
      }
      existCodeList.map(item => item.code).includes(value) ? callback(new Error(`权限标识 ${value} 重复`)) : callback()
    }
    return {
      permissionList: [],
      showDialog: false, // 是否显示弹层
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '', // 类型
        isEdit: false,
        originList: [] // 所有权限的扁平数组
      },
      rules: {
        name: [
          { required: true, message: '权限名称不能为空', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '权限标识不能为空', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    // 获取全部角色列表
    async getPermissionList() {
      const res = await getPermissionList()
      this.permissionList = transListToTree(res.data, '0')
      this.originList = res.data
    },
    // 新增或编辑权限
    onSubmit() {
      this.$refs.perForm.validate(valid => {
        if (!valid) return
        this.isEdit ? this.editPerm() : this.addPerm()
      })
    },
    // 添加权限按钮
    addPermBtn(type, id) {
      this.isEdit = false
      this.showDialog = true
      this.formData.pid = id
      this.formData.type = type
    },
    // 添加权限
    async addPerm() {
      const res = await addPermission(this.formData)
      console.log(res)
      this.$message.success(res.message)
      this.showDialog = false
      this.getPermissionList()
    },
    // 编辑权限按钮
    async editPermBtn(id) {
      this.isEdit = true
      this.showDialog = true
      const res = await getPermissionDetail(id)
      this.formData = res.data
    },
    // 编辑权限
    async editPerm() {
      const res = await updatePermission(this.formData)
      this.$message.success(res.message)
      this.showDialog = false
      this.getPermissionList()
    },
    // 删除权限
    async delPermBtn(id) {
      const confirmRes = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRes === 'cancel') return this.$message('已取消了删除')
      const res = await delPermission(id)
      this.$message.success(res.message)
      this.getPermissionList()
    },
    // 取消
    btnCancel() {
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '', // 类型
        isEdit: false
      }
      this.$refs.perForm.resetFields()
      this.showDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.el-row.is-justify-end.el-row--flex {
    margin-bottom: 20px;
}
</style>
